﻿using System;
using System.Collections.Generic;
using System.Text;
using YL.Core.Entity;
using SqlSugar;
using IServices;
using IRepository;
using YL.Utils.Table;
using YL.Utils.Json;
using YL.Utils.Extensions;
using YL.Core.Dto;
using YL.Utils.Pub;
using YL.Utils.Security;

namespace Services
{
    public class Whr_userServices : BaseServices<Whr_user>, IWhr_userServices
    {
        private readonly SqlSugarClient _client;

        private readonly IWhr_userRepository _userRepository;

        public Whr_userServices(SqlSugarClient client, IWhr_userRepository repository) : base(repository)
        {
            _client = client;
            _userRepository = repository;
        }

        public (int, List<Whr_user>) PageList(Bootstrap.BootstrapParams bootstrap) 
        {
            var totalNumber = 0;
            var query = _client.Queryable<Whr_user>();           
            var result = query.ToPageList(bootstrap.offset, bootstrap.limit, ref totalNumber);
            return (totalNumber, result);
        }

        public (bool, string, Whr_user) CheckLogin(Whr_user dto) 
        {
            var flag = false;
            if (dto.IsNull()) 
            {               
                return (flag, PubConst.Login2, null);
            }
            var user = _userRepository.QueryableToEntity(c => c.Mobile == dto.Mobile);  
            if (user == null)
            {
                return (flag, PubConst.Login2, null);
            }
            else 
            {
                //验证密码使用Bcrypt
                var validPassword = BCrypt.Net.BCrypt.Verify(dto.Password, user.Password);
                if (!validPassword) 
                {                    
                    return (flag, PubConst.Login2, null);
                }
            }
            flag = true;
            //暂时返回这两个值
            return (flag, PubConst.Login1, dto);
        }

        public void Login(int userId, string ip) 
        {
            var op = _client.Updateable(new Whr_user
            {
                UserId = userId,
                LoginDateTime = DateTimeExt.GetUnixTimestamp(),
                LoginIp = ip
            }).UpdateColumns(d => new 
            { 
                d.LoginIp,
                d.LoginDateTime,
                d.LoginTime
            }).ReSetValue(c => c.LoginTime == c.LoginTime + 1).ExecuteCommand();
        }

        public (bool, string) RegisterAndBind(string phone, int wechatId) 
        {
            var wechatInfo = _client.Queryable<Whr_wechat>().Where(it => it.Id == wechatId);
            if (wechatInfo == null) 
            {
                return (false, "登录信息有误，请重新登录");
            }

            var userInfo = _client.Queryable<Whr_user>().Where(it => it.Mobile == phone).First();

            var rel = _client.Queryable<Whr_user_wechat_rel>().Where(it => it.WechatUserId == wechatId).First();

            if (rel != null)
            {
                return (false, "你已绑定手机号码，不能再进行绑定");
            }

            if (userInfo == null)
            {                
                try
                {
                    _client.BeginTran();
                    var userId = _client.Insertable(new Whr_user
                    {
                        Mobile = phone,
                        CreateAt = DateTimeExt.DateTime
                    }).ExecuteReturnIdentity();
                    _client.Insertable(new Whr_user_wechat_rel
                    {
                        UserId = userId,
                        WechatUserId = wechatId
                    }).ExecuteCommand();
                    _client.CommitTran();
                    return (true, "");
                }
                catch
                {
                    _client.RollbackTran();
                    return (false, "写入数据失败");
                }
            }
            else 
            {
                if (rel.UserId != userInfo.UserId) 
                {
                    return (false, "你已绑定手机号码，不能再进行绑定");
                }
                return (false, "");
            }

        } 
    }
}
